package com.jinke.api.modules.ums.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinke.api.common.api.CommonPage;
import com.jinke.api.common.api.CommonResult;
import com.jinke.api.modules.ums.model.ApiLog;
import com.jinke.api.modules.ums.request.ApiLogRequest;
import com.jinke.api.modules.ums.service.IApiLogService;
import com.jinke.api.modules.ums.vo.ApiLogVO;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/apiLog")
@RequiredArgsConstructor
public class ApiLogController {
    private final IApiLogService apiLogService;

    @ApiOperation("用户渠道列表")
    @GetMapping("/list")
    @ResponseBody
    public CommonResult<CommonPage<ApiLogVO>> list(ApiLogRequest request) {
        Page<ApiLog> apiLogPage = Optional.ofNullable(
                apiLogService.page(
                        new Page<>(request.getPageNum(), request.getPageSize()),
                        Wrappers.<ApiLog>lambdaQuery()
                                .like(StrUtil.isNotBlank(request.getOrderNo()), ApiLog::getOrderNo, request.getOrderNo())
                                .eq(StrUtil.isNotBlank(request.getRequestTypeName()), ApiLog::getRequestTypeName, request.getRequestTypeName())
                                .select(ApiLog::getOrderNo, ApiLog::getRequestTypeName, ApiLog::getResult, ApiLog::getCreateTime)
                                .orderByDesc(ApiLog::getCreateTime))
        ).orElse(new Page<ApiLog>());
        return CommonResult.success(CommonPage.restPage(
                new Page<ApiLogVO>()
                        .setCurrent(apiLogPage.getCurrent())
                        .setSize(apiLogPage.getSize())
                        .setTotal(apiLogPage.getTotal())
                        .setRecords(
                                Optional.ofNullable(apiLogPage.getRecords()).orElse(Lists.newArrayList()).stream().map(apiLog -> {
                                    ApiLogVO apiLogVO = new ApiLogVO();
                                    BeanUtils.copyProperties(apiLog, apiLogVO);
                                    return apiLogVO;
                                }).collect(Collectors.toList())
                        )));
    }
}
